<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow>
      <el-alert
        title="注意：只允许第三季分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <el-form ref="sortForm">
        <el-form-item label="选择商品分类">
          <el-cascader
            placeholder="请选择"
            :options="options"
            :props="{
              label: 'cat_name',
              value: 'cat_id',
            }"
            clearable
            v-model="newSortArr"
            @change="setNewSortArr"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="first">
          <el-button
            type="primary"
            @click="addParamsVisible = true"
            size="mini"
            :disabled="disabled1"
            >添加参数</el-button
          ></el-tab-pane
        >
        <el-tab-pane label="静态属性" name="second"
          ><el-button
            type="primary"
            @click="addParamsVisible = true"
            size="mini"
            :disabled="disabled2"
            >添加属性</el-button
          ></el-tab-pane
        >
      </el-tabs>
      <el-table border :data="sorts2" v-loading="loading">
        <el-table-column
          type="expand"
          label="明细"
          width="50"
          #default="{ row }"
        >
          <!-- slot-scope="props" -->
          <template>
            <el-form label-position="left" inline class="demo-table-expand">
              <div class="rolesDate">
                <el-form-item>
                  <el-tag
                    v-show="tag.length != 0"
                    :key="index"
                    v-for="(tag, index) in row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(row, tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="inputVisible"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm(row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput"
                    >+ New Tag</el-button
                  >
                </el-form-item>
              </div>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="序号" width="50" type="index">
        </el-table-column>
        <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
        <el-table-column label="操作" #default="{ row }">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            class="updateRole"
            @click="showUpdatePage(row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteParams(row)"
            >删除</el-button
          >
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加动态和静态属性 -->
    <el-dialog :title="title" :visible.sync="addParamsVisible">
      <el-form :model="sort" ref="addParamForm" :rules="$rules.good">
        <el-form-item prop="attr_name" :label="label" label-width="80px">
          <el-input v-model="sort.attr_name"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑动态和静态属性 -->
    <el-dialog :title="title" :visible.sync="updateParamsVisible">
      <el-form :model="sort2" ref="updateParamForm" :rules="$rules.good">
        <el-form-item prop="attr_name" :label="label" label-width="80px">
          <el-input v-model="sort2.attr_name"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateParams()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeName: "first",
      options: [],
      newSortArr: [],
      sorts: [],
      sort: {
        id: "",
        sel: "many",
        attr_name: "",
      },
      sort2: {
        id: "",
        attrId: "",
        attr_sel: "many",
        attr_name: "",
        attr_vals: "",
      },
      title: "添加动态参数",
      label: "动态参数",
      sorts2: [],
      disabled1: true,
      disabled2: true,
      addParamsVisible: false,
      updateParamsVisible: false,
      inputVisible: false,
      inputValue: "",
    };
  },
  methods: {
    //拿到下拉框页面所有商品分类数据(不传pagenum和pagesize,传type)
    async initAllSortsList() {
      try {
        this.loading = true;
        let sorts = await this.$api.getSortsList({
          type: 3,
        });
        if (sorts == "error") return;
        this.options = sorts;
        // this.options.label=this.options.cat_name
        // console.log("初始化数据333", sorts);
      } catch (error) {
        console.log("RoleView-initSortsList-error:", error);
      } finally {
        this.loading = false;
      }
    },
    //设置sel,并重新刷新获取的页面
    handleClick() {
      if (this.sorts2.length == 0) return;
      if (this.activeName == "first") {
        this.sort.sel = "many";
        this.title = "添加动态参数";
        this.label = "动态参数";
        this.getParameList();
      } else {
        this.sort.sel = "only";
        this.title = "添加静态属性";
        this.label = "静态属性";
        this.getParameList();
      }
    },
    //因为级联返回的是数组，所以通过@change拿到级联级别
    setNewSortArr() {
      //   console.log("setNewSortArr", this.newSortArr);
      let leg = this.newSortArr.length;
      if (leg == 0) {
        this.sort.id = 0;
        this.sort.sel = "many";
      } else {
        this.sort.id = this.newSortArr[leg - 1];
      }
      this.getParameList();
    },
    //获得参数页面
    async getParameList() {
      this.sorts2 = [];
      let data = await this.$api.getParameListById(this.sort.id, {
        sel: this.sort.sel,
      });
      console.log(222, data);
      this.sorts2 = data;
      if (this.newSortArr.length == 0) {
        this.disabled1 = true;
        this.disabled2 = true;
      } else {
        this.disabled1 = false;
        this.disabled2 = false;
      }
      for (let item of data) {
        let attr_vals = item.attr_vals.split(",");
        // console.log("hhh", attr_vals);
        item.attr_vals = attr_vals;
      }
    },
    //添加参数和属性
    async addParams() {
      try {
        await this.$refs.addParamForm.validate();
        let data = await this.$api.addParameListById(this.sort.id, {
          attr_sel: this.sort.sel,
          attr_name: this.sort.attr_name,
        });
        if (data == "error") return;
        this.$message.success("添加成功");
        this.getParameList();
        this.initAllSortsList();
        this.addParamsVisible = false;
        // console.log(111, data);
      } catch (error) {
        console.log("addParams-error:", error);
      }
    },
    //展示修改页面
    showUpdatePage(row) {
      this.updateParamsVisible = true;
      this.title = `修改${this.label}`;
      //   this.sort2 = row;
      this.sort2 = {
        //拷贝，因为对象是引用类型，防止v-mole动态变化
        id: row.cat_id,
        attrId: row.attr_id,
        attr_sel: row.attr_sel,
        attr_name: row.attr_name,
        attr_vals: row.attr_vals,
      };
      //   console.log(11, row, 22, this.sort2);
    },
    //编辑参数
    async updateParams() {
    //   console.log(this.title, this.label, this.sort2);
      try {
        await this.$refs.updateParamForm.validate();
        let params = {
          attr_sel: this.sort2.attr_sel,
          attr_name: this.sort2.attr_name,
        };
        let data = await this.$api.updateParameListByIdAndAttrId(
          this.sort2.id,
          this.sort2.attrId,
          params
        );
        // console.log(111, data);
        if (data == "error") return;
        this.$message.success("修改成功");
        this.getParameList();
        this.initAllSortsList();
        this.updateParamsVisible = false;
      } catch (error) {
        console.log("updateParams-error:", error);
      }
    },
    //删除参数
    async deleteParams(row) {
      //   console.log('deleteParamsRow',row);
      try {
        let data = await this.$api.deleteParameListByIdAndAttrId(
          row.cat_id,
          row.attr_id
        );
        // console.log(111, data);
        if (data == "error") return;
        this.$message.success("删除成功");
        this.getParameList();
        this.initAllSortsList();
      } catch (error) {
        console.log("deleteParams-error:", error);
      }
    },
    //删除参数标签
    async handleClose(row, tag) {
      try {
        // console.log("handleClose", row, tag);
        row.attr_vals.splice(row.attr_vals.indexOf(tag), 1);
        let attr_vals = row.attr_vals.join(",");
        // console.log(123, attr_vals);
        let params = {
          attr_sel: row.attr_sel,
          attr_name: row.attr_name,
          attr_vals: attr_vals,
        };
        let data = await this.$api.updateParameListByIdAndAttrId(
          row.cat_id,
          row.attr_id,
          params
        );
        console.log(111, data);
        if (data == "error") return;
        this.$message.success("删除成功");
      } catch (error) {
        console.log("handleClose-error:", error);
      }
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 添加参数标签
    async handleInputConfirm(row) {
      try {
        if (this.inputValue) {
          row.attr_vals.push(this.inputValue);
        }
        // console.log("添加参数标签", row, this.inputValue);
        let attr_vals = row.attr_vals.join(",");
        let params = {
          attr_sel: row.attr_sel,
          attr_name: row.attr_name,
          attr_vals: attr_vals,
        };
        let data = await this.$api.updateParameListByIdAndAttrId(
          row.cat_id,
          row.attr_id,
          params
        );
        // console.log(111, data);
        if (data == "error") return;
        this.$message.success("添加成功");
      } catch (error) {
        console.log("handleInputConfirm-error:", error);
      } finally {
        this.inputVisible = false;
        this.inputValue = "";
      }
    },
  },

  created() {
    this.initAllSortsList();
  },
};
</script>
<style lang="less" scoped>
.el-form {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.rolesDate {
  padding: 0 50px;

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}
.el-form {
  margin-top: 10px;
}
</style>